<template>
  <div class="search-page">
    <div class="page-header">
      <h1 class="page-title">高级搜索</h1>
      <p class="page-subtitle">使用多种条件精确搜索文档</p>
    </div>

    <div class="search-content">
      <div class="search-form-container">
        <el-card shadow="never">
          <template #header>
            <div class="form-header">
              <el-icon><Search /></el-icon>
              <span>搜索条件</span>
            </div>
          </template>
          
          <el-form :model="searchForm" label-width="100px">
            <el-form-item label="关键词">
              <el-input
                v-model="searchForm.keyword"
                placeholder="输入关键词..."
                clearable
              />
            </el-form-item>
            
            <el-form-item label="文件类型">
              <el-checkbox-group v-model="searchForm.types">
                <el-checkbox value="pdf">PDF</el-checkbox>
                <el-checkbox value="doc">Word</el-checkbox>
                <el-checkbox value="ppt">PowerPoint</el-checkbox>
                <el-checkbox value="img">图片</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            
            <el-form-item label="关联项目">
              <el-select
                v-model="searchForm.projectIds"
                multiple
                placeholder="选择项目"
                style="width: 100%"
              >
                <el-option
                  v-for="project in projectStore.projects"
                  :key="project.id"
                  :label="project.name"
                  :value="project.id"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="performSearch" :loading="searching">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <div class="search-results-container">
        <el-card shadow="never">
          <template #header>
            <div class="results-header">
              <span>搜索结果</span>
              <span v-if="searchResults.length" class="result-count">
                共找到 {{ searchResults.length }} 个文档
              </span>
            </div>
          </template>
          
          <div v-if="!hasSearched" class="empty-state">
            <el-icon class="empty-icon"><Search /></el-icon>
            <div class="empty-title">开始搜索</div>
            <div class="empty-description">设置搜索条件后点击搜索按钮</div>
          </div>
          
          <div v-else-if="!searchResults.length" class="empty-state">
            <el-icon class="empty-icon"><DocumentDelete /></el-icon>
            <div class="empty-title">未找到相关文档</div>
            <div class="empty-description">请尝试修改搜索条件</div>
          </div>
          
          <div v-else class="results-list">
            <div
              v-for="doc in searchResults"
              :key="doc.id"
              class="result-item"
              @click="previewDocument(doc)"
            >
              <div class="result-icon" :class="doc.type">
                <el-icon>
                  <Document v-if="doc.type === 'pdf'" />
                  <Reading v-else-if="doc.type === 'doc'" />
                  <Present v-else-if="doc.type === 'ppt'" />
                  <Picture v-else />
                </el-icon>
              </div>
              
              <div class="result-content">
                <div class="result-title" v-html="highlightKeyword(doc.title, searchForm.keyword)"></div>
                <div class="result-description" v-html="highlightKeyword(doc.description, searchForm.keyword)"></div>
                <div class="result-meta">
                  <el-tag size="small" :color="getProjectColor(doc.project)">{{ doc.project }}</el-tag>
                  <span class="meta-item">{{ doc.size }}</span>
                  <span class="meta-item">{{ formatTime(doc.updateTime) }}</span>
                  <span class="meta-item">{{ doc.author }}</span>
                </div>
                <div class="result-tags">
                  <el-tag
                    v-for="tag in doc.tags"
                    :key="tag"
                    size="small"
                    type="info"
                    v-html="highlightKeyword(tag, searchForm.keyword)"
                  ></el-tag>
                </div>
              </div>
              
              <div class="result-actions">
                <el-button size="small" circle @click.stop="previewDocument(doc)">
                  <el-icon><View /></el-icon>
                </el-button>
                <el-button size="small" circle @click.stop="downloadDocument(doc)">
                  <el-icon><Download /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 文档预览对话框 -->
    <el-dialog
      v-model="showPreviewDialog"
      :title="currentPreviewDoc?.title"
      width="80%"
      top="5vh"
    >
      <DocumentPreview v-if="currentPreviewDoc" :document="currentPreviewDoc" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useDocumentStore } from '@/store/document'
import { useProjectStore } from '@/store/project'
import { ElMessage } from 'element-plus'
import {
  Search, Document, Reading, Present, Picture,
  DocumentDelete, View, Download
} from '@element-plus/icons-vue'
import DocumentPreview from '@/components/DocumentPreview.vue'

const documentStore = useDocumentStore()
const projectStore = useProjectStore()

// 响应式数据
const searching = ref(false)
const hasSearched = ref(false)
const searchResults = ref([])
const showPreviewDialog = ref(false)
const currentPreviewDoc = ref(null)

const searchForm = reactive({
  keyword: '',
  types: [],
  projectIds: [],
  dateRange: null
})

// 计算属性
const isFormEmpty = computed(() => {
  return !searchForm.keyword.trim() &&
         !searchForm.types.length &&
         !searchForm.projectIds.length &&
         !searchForm.dateRange
})

// 方法
const performSearch = async () => {
  if (isFormEmpty.value) {
    ElMessage.warning('请设置至少一个搜索条件')
    return
  }
  
  searching.value = true
  hasSearched.value = true
  
  try {
    // 模拟搜索延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    
    let results = [...documentStore.documents]
    
    // 关键词搜索
    if (searchForm.keyword.trim()) {
      const keyword = searchForm.keyword.toLowerCase()
      results = results.filter(doc =>
        doc.title.toLowerCase().includes(keyword) ||
        doc.description.toLowerCase().includes(keyword) ||
        doc.tags.some(tag => tag.toLowerCase().includes(keyword)) ||
        doc.author.toLowerCase().includes(keyword)
      )
    }
    
    // 类型筛选
    if (searchForm.types.length) {
      results = results.filter(doc => searchForm.types.includes(doc.type))
    }
    
    // 项目筛选
    if (searchForm.projectIds.length) {
      results = results.filter(doc => searchForm.projectIds.includes(doc.projectId))
    }
    
    // 时间范围筛选
    if (searchForm.dateRange) {
      const [startDate, endDate] = searchForm.dateRange
      results = results.filter(doc => {
        const docDate = new Date(doc.updateTime).toISOString().split('T')[0]
        return docDate >= startDate && docDate <= endDate
      })
    }
    
    searchResults.value = results
    
    if (results.length) {
      ElMessage.success(`找到 ${results.length} 个匹配的文档`)
    } else {
      ElMessage.info('未找到匹配的文档，请尝试其他搜索条件')
    }
    
  } finally {
    searching.value = false
  }
}

const resetForm = () => {
  searchForm.keyword = ''
  searchForm.types = []
  searchForm.projectIds = []
  searchForm.dateRange = null
  searchResults.value = []
  hasSearched.value = false
}

const highlightKeyword = (text, keyword) => {
  if (!keyword || !keyword.trim()) return text
  
  const regex = new RegExp(`(${keyword.trim()})`, 'gi')
  return text.replace(regex, '<mark>$1</mark>')
}

const getProjectColor = (projectName) => {
  const project = projectStore.projects.find(p => p.name === projectName)
  return project ? project.color : '#909399'
}

const formatTime = (timeStr) => {
  const time = new Date(timeStr)
  return time.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

const previewDocument = (doc) => {
  currentPreviewDoc.value = doc
  showPreviewDialog.value = true
  documentStore.incrementUsageCount(doc.id)
}

const downloadDocument = (doc) => {
  ElMessage.success(`开始下载：${doc.title}`)
  documentStore.incrementUsageCount(doc.id)
}

// 初始化 - 检查是否有来自全局搜索的关键词
onMounted(() => {
  if (documentStore.searchKeyword) {
    searchForm.keyword = documentStore.searchKeyword
    searchResults.value = documentStore.searchResults
    hasSearched.value = true
  }
})
</script>

<style lang="scss" scoped>
.search-page {
  padding: 20px;
  height: calc(100vh - 60px);
  overflow: auto;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
  
  .page-title {
    font-size: 28px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin-bottom: 8px;
  }
  
  .page-subtitle {
    color: var(--el-text-color-secondary);
    font-size: 14px;
  }
}

.search-content {
  display: grid;
  grid-template-columns: 350px 1fr;
  gap: 24px;
  height: calc(100% - 120px);
}

.search-form-container {
  .form-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.search-results-container {
  .results-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    color: var(--el-text-color-primary);
    
    .result-count {
      font-size: 14px;
      color: var(--el-text-color-secondary);
      font-weight: normal;
    }
  }
  
  .results-list {
    max-height: 600px;
    overflow-y: auto;
    
    .result-item {
      display: flex;
      gap: 16px;
      padding: 16px 0;
      border-bottom: 1px solid var(--el-border-color-lighter);
      cursor: pointer;
      transition: background-color 0.2s;
      
      &:hover {
        background: var(--el-fill-color-lighter);
        margin: 0 -16px;
        padding-left: 16px;
        padding-right: 16px;
        border-radius: 8px;
        
        .result-actions {
          opacity: 1;
        }
      }
      
      &:last-child {
        border-bottom: none;
      }
      
      .result-icon {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        color: white;
        flex-shrink: 0;
        
        &.pdf { background: var(--gradient-danger); }
        &.doc { background: var(--gradient-primary); }
        &.ppt { background: var(--gradient-warning); }
        &.img { background: var(--gradient-success); }
      }
      
      .result-content {
        flex: 1;
        min-width: 0;
        
        .result-title {
          font-size: 16px;
          font-weight: 600;
          color: var(--el-text-color-primary);
          margin-bottom: 8px;
          line-height: 1.4;
          
          :deep(mark) {
            background: var(--el-color-warning-light-7);
            color: var(--el-color-warning-dark-2);
            padding: 2px 4px;
            border-radius: 3px;
          }
        }
        
        .result-description {
          font-size: 14px;
          color: var(--el-text-color-secondary);
          line-height: 1.5;
          margin-bottom: 12px;
          @extend .text-ellipsis-2;
          
          :deep(mark) {
            background: var(--el-color-warning-light-7);
            color: var(--el-color-warning-dark-2);
            padding: 2px 4px;
            border-radius: 3px;
          }
        }
        
        .result-meta {
          display: flex;
          gap: 12px;
          align-items: center;
          margin-bottom: 8px;
          font-size: 13px;
          color: var(--el-text-color-placeholder);
          
          .meta-item {
            display: flex;
            align-items: center;
          }
        }
        
        .result-tags {
          display: flex;
          gap: 6px;
          flex-wrap: wrap;
          
          .el-tag {
            margin: 0;
            
            :deep(mark) {
              background: var(--el-color-warning-light-7);
              color: var(--el-color-warning-dark-2);
              padding: 1px 2px;
              border-radius: 2px;
            }
          }
        }
      }
      
      .result-actions {
        display: flex;
        gap: 8px;
        align-items: flex-start;
        opacity: 0;
        transition: opacity 0.2s;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .search-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .search-form-container {
    order: 2;
  }
  
  .search-results-container {
    order: 1;
  }
}
</style>